﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace VeryExtremeArt.Controller
{
    public class BidController
    {
        public Bid GetBid(int auctionedItemId, int memberId)
        {
            using (DataBaseDataContext db = new DataBaseDataContext())
            {
                return db.Bids.SingleOrDefault(b => (b.AuctionedItemId == auctionedItemId) && (b.MemberId == memberId));
            }
        }

        public Bid placeBid(int auctionedItemId, int memberId, decimal bidPrice)
        {
            Bid bid = new Bid();
            bid.AuctionedItemId = auctionedItemId;
            bid.MemberId = memberId;
            bid.CurrentBid = bidPrice;

            Bid existingBid = GetBid(auctionedItemId, memberId);
            if (existingBid != null)
            {
                if (existingBid.CurrentBid < bidPrice)
                {
                    updateBid(auctionedItemId, memberId, bidPrice);
                    return existingBid;
                }
                else
                    return null;
            }
            else
            {

                using (DataBaseDataContext db = new DataBaseDataContext())
                {

                    try
                    {
                        db.Bids.InsertOnSubmit(bid);
                        db.SubmitChanges();
                        return bid;

                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
            }
        }

        public void updateBid(int auctionedItemId, int memberId, decimal bidPrice)
        {
            //Bid b = new Bid();
            //b = GetBid(auctionedItemId, memberId);
            //b.CurrentBid = bidPrice;
            using (DataBaseDataContext db = new DataBaseDataContext())
            {
                try
                {
                    db.Bids.SingleOrDefault(b => b.AuctionedItemId == auctionedItemId && b.MemberId == memberId).CurrentBid = bidPrice;
                    db.SubmitChanges();                  
                }
                catch (Exception e)
                {
                    throw e;
                }
               
            }

        }
    }
}